package com.zijie.system.service;

import cn.dev33.satoken.secure.BCrypt;
import com.zijie.common.core.constant.CacheConstants;
import com.zijie.common.core.constant.CacheNames;
import com.zijie.common.core.constant.Constants;
import com.zijie.common.core.domain.bo.RegisterBody;
import com.zijie.common.core.enums.UserType;
import com.zijie.common.core.exception.user.CaptchaException;
import com.zijie.common.core.exception.user.CaptchaExpireException;
import com.zijie.common.core.exception.user.UserException;
import com.zijie.common.core.utils.MessageUtils;
import com.zijie.common.core.utils.ServletUtils;
import com.zijie.common.core.utils.SpringUtils;
import com.zijie.common.core.utils.StringUtils;
import com.zijie.common.log.event.LogininforEvent;
import com.zijie.common.redis.utils.RedisUtils;
import com.zijie.common.web.config.properties.CaptchaProperties;
import com.zijie.system.domain.bo.SysUserBo;
import com.zijie.system.mapper.SysUserRoleMapper;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 注册校验方法
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysRegisterService {

    private final SysUserService userService;
    private final CaptchaProperties captchaProperties;
    @Autowired
    RedissonClient redissonClient;
    /**
     * 管理员注册
     */
    public void register(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
         String email = registerBody.getEmail();
        // 校验用户类型是否存在
        String userType = UserType.getUserType(registerBody.getUserType()).getUserType();

      //  boolean captchaEnabled = captchaProperties.getEnable();
        String captchaEnabled = (String) redissonClient.getMap(CacheNames.SYS_CONFIG).get("sys.account.captchaEnabled");
        // 验证码开关
        if (Boolean.parseBoolean(captchaEnabled)) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }
        SysUserBo sysUser = new SysUserBo();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(userType);
        sysUser.setEmail( email);
        // 设置部门id
         sysUser.setDeptId(103L);
         // 设置状态
         sysUser.setStatus("1");

        if (!userService.checkUserNameUnique(sysUser)) {
            throw new UserException("user.register.save.error", username);
        }
        if (userService.checkEmailUnique(email)) {
            throw new UserException("user.email.save.error", email);
        }

        boolean regFlag = userService.registerUser(sysUser);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }
        recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }


    /**
     * 用户注册
     */
    public void userRegister(RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        String email = registerBody.getEmail();
        // 校验用户类型是否存在
        String userType = UserType.getUserType(registerBody.getUserType()).getUserType();

        //  boolean captchaEnabled = captchaProperties.getEnable();
        String captchaEnabled = (String) redissonClient.getMap(CacheNames.SYS_CONFIG).get("sys.account.captchaEnabled");
        // 验证码开关
        if (Boolean.parseBoolean(captchaEnabled)) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }
        SysUserBo sysUser = new SysUserBo();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(userType);
        sysUser.setEmail( email);
        // 设置部门id
        sysUser.setDeptId(105L);
        // 设置状态
        sysUser.setStatus("1");

        if (!userService.checkUserNameUnique(sysUser)) {
            throw new UserException("user.register.save.error", username);
        }
        if (userService.checkEmailUnique(email)) {
            throw new UserException("user.email.save.error", email);
        }
        boolean regFlag = userService.userregisterUser(sysUser);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }
        recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }


    /**
     * 用户注册
     */
    public void wxuserRegister(String openId ) {


        SysUserBo sysUser = new SysUserBo();
        sysUser.setUserName(openId);
        sysUser.setNickName("无名氏");
        sysUser.setRemark("这个家伙很懒");
        sysUser.setAvatar("http://115.190.80.129:9000/zijie/2025/05/06/306a5d84fcf54ba5bfb59afbd2588fca.jpg");
        //默认密码
        sysUser.setPassword(BCrypt.hashpw("123gfgfdgd34434"));
        sysUser.setUserType("sys_user");
        // 设置部门id
        sysUser.setDeptId(105L);
        // 设置状态
        sysUser.setStatus("1");
        boolean regFlag = userService.userregisterUser(sysUser);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }
        recordLogininfor(openId, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");

        String captcha = RedisUtils.getCacheObject(verifyKey);

        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    private void recordLogininfor(String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

}
